// translate router.meta.title, be used in breadcrumb sidebar tagsview
import { getI18n } from '../api/common'
import Cookies from 'js-cookie'
import store from '@/store'

const langKey = 'i18nKey'
export function generateTitle(title) {
  const hasKey = this.$te('route.' + title)
  const translatedTitle = this.$t('route.' + title) // $t :this method from vue-i18n, inject in @/lang/index.js

  if (hasKey) {
    return translatedTitle
  }
  return title
}

export function getHelpMeaning(meaning, key) {
  const lang = Cookies.get('language') || 'en_US'
  return meaning[lang][key] || key
}

export function clearI18() {
  localStorage.removeItem(langKey)
  store.dispatch('clearI18')
}

export function getI18nByKeys(textIds) {
  return new Promise((resolve, reject) => {
    const newTextIds = []
    const result = {}
    // const langLs = JSON.parse(localStorage.getItem(langKey)) || {}
    const langLs = store.getters.i18Meaning
    textIds.forEach(element => {
      if (!langLs[element]) {
        newTextIds.push(element)
      } else {
        result[element] = langLs[element]
      }
    })
    if (newTextIds.length > 0) {
      getI18n(newTextIds).then(response => {
        const data = response.data
        if (data.data) {
          const i18ns = data.data
          for (const key in i18ns) {
            if (!i18ns[key] || i18ns[key] === 'null') {
              delete i18ns[key]
            }
          }
          // const langLs = JSON.parse(localStorage.getItem(langKey)) || {}
          // Object.assign(langLs, i18ns)
          // localStorage.setItem(langKey, JSON.stringify(langLs))
          store.dispatch('addI18', i18ns)
        }
        textIds.forEach(element => {
          if (langLs[element]) {
            result[element] = langLs[element]
          }
        })
        resolve(result)
      })
    } else {
      resolve(result)
    }
  })
}
